package com.penglecode.netty3.example1;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务端处理器
 * 
 * 场景一：client端应用程序是强制结束,即对于server端来说表现的是：远程主机强迫关闭了一个现有的连接,
 * 		      那么ServerHandler中的执行顺序依次是：exceptionCaught(..),channelDisconnected(..),channelClosed(..)
 * 
 * 
 * @author pengpeng
 * @date 2013-6-26下午2:15:08
 * @version 1.0
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class EchoServerHandler extends SimpleChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);
	
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		logger.error("server internal error!", e.getCause());
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		logger.debug("[server] channel = {}", e.getChannel());
		logger.debug("[server] received message from client = {}", MessageUtils.getMessage(e.getMessage()));
		logger.debug("[server] remoteAddress = {}", e.getRemoteAddress());
		e.getChannel().write(e.getMessage()); // echo
	}

	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.debug("[server] channel = {}", e.getChannel());
		logger.debug("[server] state = {}", e.getState());
		logger.debug("[server] a client channel closed!");
	}

	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.debug("[server] channel = {}", e.getChannel());
		logger.debug("[server] state = {}", e.getState());
		logger.debug("[server] a client channel connected!");
	}

	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		logger.debug("[server] channel = {}", e.getChannel());
		logger.debug("[server] state = {}", e.getState());
		logger.debug("[server] a client channel disconnected!");
	}

}
